﻿Imports System.Linq
Imports System.Xml
Imports System.Xml.Linq
Imports System.Text
Imports System.Web
Imports System.Net
Imports System.IO




''' <summary>
''' this is the class that will manage the functions used to access the 
''' </summary>
''' <remarks></remarks>
Public Class AFileSocialConn
    
    Private Const FILE_SIZE_MAX As Long = 50000000
    Private Const FS_UPLOAD_URL As String = "http://filesocial.com/api/upload"
    Private Const FS_UPLOADPOST_URL As String = "http://filesocial.com/api/uploadAndPost"
    Private Const FS_INFO_URL As String = "http://filesocial.com/api/info/"

    ''' <summary>
    ''' Uploads a file to the <a href="http://www.filesocial.com/">filesocial website</a> without actually posting it to Twitter
    ''' </summary>
    ''' <param name="p_strFileName"></param>
    ''' <param name="p_strUserName"></param>
    ''' <param name="p_strPassword"></param>
    ''' <param name="p_strMessage"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function UploadFile(ByVal p_strFileName As String, ByVal p_strUserName As String, ByVal p_strPassword As String, ByVal p_strMessage As String) As AFileSocialResponse
        Try
            Dim BinaryData As Byte() = System.IO.File.ReadAllBytes(p_strFileName)
            If BinaryData.Length > FILE_SIZE_MAX Then
                Throw New AFSException("Error: File exceeds limits")
            End If
            Dim boundary As String = Guid.NewGuid.ToString()
            Dim Header As String = String.Format("--{0}", boundary)
            Dim Footer As String = String.Format("--{0}--", boundary)
            Dim Request As HttpWebRequest = DirectCast(WebRequest.Create(FS_UPLOAD_URL), HttpWebRequest)
            With Request
                .PreAuthenticate = True
                .AllowWriteStreamBuffering = True
                .ContentType = String.Format("multipart/form-data; boundary={0}", boundary)
                .Method = "POST"
            End With
            Dim FileContentType As String = "application/octet-stream"
            Dim FileHeader As String = [String].Format("Content-Disposition: file; name=""{0}""; filename=""{1}""", "file", p_strFileName)
            Dim FileData As String = Encoding.GetEncoding("iso-8859-1").GetString(BinaryData)

            Dim Contents As New StringBuilder()
            With Contents
                .AppendLine(Header)

                .AppendLine(FileHeader)
                .AppendLine([String].Format("Content-Type: {0}", FileContentType))
                .AppendLine()
                .AppendLine(FileData)

                .AppendLine(Header)
                .AppendLine([String].Format("Content-Disposition: form-data; name=""{0}""", "username"))
                .AppendLine()
                .AppendLine(p_strUserName)

                .AppendLine(Header)
                .AppendLine([String].Format("Content-Disposition: form-data; name=""{0}""", "password"))
                .AppendLine()
                .AppendLine(p_strPassword)


                If Not String.IsNullOrEmpty(p_strMessage) Then
                    .AppendLine(Header)
                    .AppendLine([String].Format("Content-Disposition: form-data; name=""{0}""", "message"))
                    .AppendLine()
                    .AppendLine(p_strMessage)
                End If

                .AppendLine(Footer)

                Dim Bytes As Byte() = Encoding.GetEncoding("iso-8859-1").GetBytes(Contents.ToString())
                Request.ContentLength = Bytes.Length

                Using requestStream As Stream = Request.GetRequestStream()
                    requestStream.Write(Bytes, 0, Bytes.Length)

                    Using Response As HttpWebResponse = DirectCast(Request.GetResponse(), HttpWebResponse)
                        Using Reader As New StreamReader(Response.GetResponseStream())
                            Dim Result As String = Reader.ReadToEnd()

                            Dim ResponseDoc As New XmlDocument

                            'My.Computer.Clipboard.SetText(Result)
                            ResponseDoc.LoadXml(Result)
                            Dim rsp As XmlNode = ResponseDoc.SelectSingleNode("//rsp")

                            If rsp.Attributes("status").Value = "ok" Then

                                UploadFile.ResponseType = fsResponseType.fsUpload
                                UploadFile.MediaID = rsp.SelectSingleNode("//mediaid").InnerText
                                UploadFile.MediaURL = rsp.SelectSingleNode("//mediaurl").InnerText

                                'ReturnValue = rsp.SelectSingleNode("//mediaurl").InnerText
                                'ReturnValue = Result

                            End If
                        End Using
                    End Using
                End Using
            End With

        Catch ex As Exception

        End Try
        Return UploadFile

    End Function

    Public Function UploadAndPost(ByVal p_strFileName As String, ByVal p_strUserName As String, ByVal p_strPassword As String, ByVal p_strMessage As String) As AFileSocialResponse
        Try
            Dim BinaryData As Byte() = System.IO.File.ReadAllBytes(p_strFileName)
            If BinaryData.Length > FILE_SIZE_MAX Then
                Throw New AFSException("Error: File exceeds limits")
            End If
            Dim boundary As String = Guid.NewGuid.ToString()
            Dim Header As String = String.Format("--{0}", boundary)
            Dim Footer As String = String.Format("--{0}--", boundary)
            Dim Request As HttpWebRequest = DirectCast(WebRequest.Create(FS_UPLOADPOST_URL), HttpWebRequest)
            With Request
                .PreAuthenticate = True
                .AllowWriteStreamBuffering = True
                .ContentType = String.Format("multipart/form-data; boundary={0}", boundary)
                .Method = "POST"
            End With
            Dim FileContentType As String = "application/octet-stream"
            Dim FileHeader As String = [String].Format("Content-Disposition: file; name=""{0}""; filename=""{1}""", "file", p_strFileName)
            Dim FileData As String = Encoding.GetEncoding("iso-8859-1").GetString(BinaryData)

            Dim Contents As New StringBuilder()
            With Contents
                .AppendLine(Header)

                .AppendLine(FileHeader)
                .AppendLine([String].Format("Content-Type: {0}", FileContentType))
                .AppendLine()
                .AppendLine(FileData)

                .AppendLine(Header)
                .AppendLine([String].Format("Content-Disposition: form-data; name=""{0}""", "username"))
                .AppendLine()
                .AppendLine(p_strUserName)

                .AppendLine(Header)
                .AppendLine([String].Format("Content-Disposition: form-data; name=""{0}""", "password"))
                .AppendLine()
                .AppendLine(p_strPassword)


                If Not String.IsNullOrEmpty(p_strMessage) Then
                    .AppendLine(Header)
                    .AppendLine([String].Format("Content-Disposition: form-data; name=""{0}""", "message"))
                    .AppendLine()
                    .AppendLine(p_strMessage)
                End If

                .AppendLine(Footer)

                Dim Bytes As Byte() = Encoding.GetEncoding("iso-8859-1").GetBytes(Contents.ToString())
                Request.ContentLength = Bytes.Length

                Using requestStream As Stream = Request.GetRequestStream()
                    requestStream.Write(Bytes, 0, Bytes.Length)

                    Using Response As HttpWebResponse = DirectCast(Request.GetResponse(), HttpWebResponse)
                        Using Reader As New StreamReader(Response.GetResponseStream())
                            Dim Result As String = Reader.ReadToEnd()

                            Dim ResponseDoc As New XmlDocument

                            'My.Computer.Clipboard.SetText(Result)
                            ResponseDoc.LoadXml(Result)
                            Dim rsp As XmlNode = ResponseDoc.SelectSingleNode("//rsp")

                            If rsp.Attributes("status").Value = "ok" Then

                                UploadAndPost.ResponseType = fsResponseType.fsUploadAndPost
                                UploadAndPost.MediaID = rsp.SelectSingleNode("//mediaid").InnerText
                                UploadAndPost.MediaURL = rsp.SelectSingleNode("//mediaurl").InnerText

                                'ReturnValue = rsp.SelectSingleNode("//mediaurl").InnerText
                                'ReturnValue = Result

                            End If
                        End Using
                    End Using
                End Using
            End With

        Catch ex As Exception

        End Try
        Return UploadAndPost


    End Function

    Public Function GetFile(ByVal p_strMediaID As String) As AFileSocialFile
        Dim strInfoURL As String = FS_INFO_URL & p_strMediaID & ".xml"
        Dim xFSQuery As New XmlDocument

        xFSQuery.Load(strInfoURL)
        GetFile = New AFileSocialFile

        Dim xnFileInfo As XmlNode = xFSQuery.SelectSingleNode("//file")
        If Not (xnFileInfo Is Nothing) Then
            GetFile.FileName = xnFileInfo.SelectSingleNode("//name").InnerText
            GetFile.Hash = xnFileInfo.SelectSingleNode("//hash").InnerText
            GetFile.Extension = xnFileInfo.SelectSingleNode("//extension").InnerText
            GetFile.Size = CLng(xnFileInfo.SelectSingleNode("//size").InnerText)
            GetFile.DateCreated = CDate(xnFileInfo.SelectSingleNode("//created_at").InnerText)
            GetFile.VisitCounter = CInt(xnFileInfo.SelectSingleNode("//visit_counter").InnerText)
            GetFile.CommentCounter = CInt(xnFileInfo.SelectSingleNode("//comment_counter").InnerText)
            GetFile.Message = xnFileInfo.SelectSingleNode("//message").InnerText
            Return GetFile
        End If










    End Function
End Class
